package com.situ.blog.filter;

import com.situ.blog.pojo.Admin;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

// /*代表拦截所有请求
@WebFilter(filterName = "login", urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LoginFilter.init");
    }

    //service
    // ServletRequest servletRequest = new HttpServletRequest()
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("LoginFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();
        System.out.println("uri: " + uri);
        //uri: /static/layui/layui.js
        //uri: /static/layui/css/layui.css
        //uri: /static/layui/font/iconfont.woff2
        String method = request.getParameter("method");
        System.out.println("method: " + method);
        //如果这个请求是要去完成登录的，不需要执行后面的验证是否已经登录的流程
        //这些是没有登录情况下可以访问的资源
        if (uri.startsWith("/static")  // 访问/static都放行
                || uri.equals("/page/login")
                || uri.equals("/verifyCode")
                || (uri.equals("/admin") && "login".equals(method))) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            response.sendRedirect("/page/login");
            return;
        }

        //user这个令牌不是null，用户已经登录
        //如果加了这了这句话代表放行，继续往后执行
        //1.如果后面还有filter就访问后面的filter 2.没有filter就访问后台资源
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("LoginFilter.destroy");
    }
}
